const readline = require('readline');
const fs = require('fs');
const path = require('path');
const cfg = require('../../other/config');
const jslog = require('../../other/jslog');

const maxFileSize = 1024 * 1024 * 500; //最大文件大小 超过此大小不检测 防止处理打包后的文件

/**
 * 
 * @param {绝对路径名} dirPath 
 * @param {文件名关键字} keyword 
 * @param {开始时间} startTm 
 * @param {结束时间} endTm 
 * @param {*} lObj 
 */
var traversalDir = async function (dirPath, startTm, endTm, lObj) {
    let keyword = lObj.keyword;
    if ("bilog" == lObj.logType && !keyword)
        return;
    ret = {};
    let files = fs.readdirSync(dirPath);
    for (let file of files) {
        let filePath = path.join(dirPath, file);
        let stats = fs.lstatSync(filePath);
        if (stats.size > maxFileSize)
            continue;
        if (stats.isFile() && -1 != file.indexOf(keyword)) {
            let mTime = stats.mtimeMs;
            if (startTm <= mTime && mTime <= endTm && !lObj.stop) {
                await rlFunc(filePath, lObj);
            }
        } else if (stats.isDirectory()) {
            traversalDir(filePath, startTm, endTm, lObj);
        }
    }
}

/**
 * 按行处理文件
 * @param {文件名} fileName 
 * @param {回调函数} cb 
 */
var rlFunc = async function (fileName, lObj) {
    var cb = function (line) {
        lObj.lineCb(line);
    }
    await new Promise((resolve) => {
        const rl = readline.createInterface({
            input: fs.createReadStream(fileName)
        });
        lObj.rl = rl;

        rl.on('line', cb);

        rl.on('close', function () {
            resolve();
        });
    });
}

var exec = async function (id, startTm, endTm, params) {
    let lObj = jslog[id];
    lObj.params = params;
    await traversalDir(cfg.log[lObj.logType], startTm, endTm, lObj);
    console.log(JSON.stringify(lObj.ret));
}

let args = process.argv.slice(2);
if (args.length < 4)
    return;
let id = args[0];
let startTm = args[1];
let endTm = args[2];
let params = args[3];

exec(id, startTm, endTm, params);